package com.quanshu.shop.pay;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.gui.pay.PayResult;
import com.quanshu.exchange.ui.gui.profile.AllOrderActivity;
import com.quanshu.exchange.wxapi.WXPayEntryActivity;
import com.quanshu.shop.base.data.BroadcastReciverAction;
import com.quanshu.shop.base.view.BaseTitleBar;
import com.quanshu.shop.brocastreciver.PayBrocastReciver;
import com.quanshu.shop.order.SubmitOrderActivity;
import com.quanshu.shop.order.entity.CreatOrderEntity;
import com.quanshu.shop.pay.inf.PayResultIF;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class PayCashActivity extends BaseActivity implements PayResultIF {

    @BindView(R.id.pay_cash_title)
    BaseTitleBar payCashTitle;
    @BindView(R.id.pay_cash_txt2)
    TextView payCashTxt2;
    @BindView(R.id.pay_cash_img1)
    ImageView payCashImg1;
    @BindView(R.id.pay_cash_fl1)
    FrameLayout payCashFl1;
    @BindView(R.id.pay_cash_line)
    View payCashLine;
    @BindView(R.id.pay_cash_txt3)
    TextView payCashTxt3;
    @BindView(R.id.pay_cash_img2)
    ImageView payCashImg2;
    @BindView(R.id.pay_cash_fl2)
    FrameLayout payCashFl2;
    @BindView(R.id.pay_cash_submit)
    TextView payCashSubmit;
    private Bundle getBundle;
    private CreatOrderEntity creatOrderEntity;
    private PayBrocastReciver payBrocastReciver;
    private int state = 0;
    private static final int SDK_PAY_FLAG = 1;
    private static final String TAG = "PayCashActivity";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastHelper.toast("支付成功");
                        Intent intent = new Intent(PayCashActivity.this, AllOrderActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastHelper.toast("支付失败");
                        Intent intent = new Intent(PayCashActivity.this, AllOrderActivity.class);
                        intent.putExtra("ORDER_FLAG", 1);
                        startActivity(intent);
                        finish();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay_cash);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(payBrocastReciver);
    }

    private void initView() {
        payBrocastReciver = new PayBrocastReciver().setPayResultListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadcastReciverAction.PAY_RESULT_ACTION);
        registerReceiver(payBrocastReciver, intentFilter);
        getBundle = getIntent().getExtras();
        if (getBundle != null) {
            creatOrderEntity = (CreatOrderEntity) getBundle.getSerializable(SubmitOrderActivity.CREATE_ORDER);
        }
        payCashTitle.setLeftImage(R.drawable.icon_back_black_2_0).setCenterText("现金订单支付").setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
            @Override
            public void onclickLeft() {
                finish();
            }

            @Override
            public void onclickRight() {

            }
        });

        RxViewHelper.getInstance().clicks(payCashFl1, aVoid ->
                {
                    //点击微信支付
                    state = 0;
                    payCashImg1.setImageResource(R.drawable.icon_selected_2_0);
                    payCashImg2.setImageResource(R.drawable.icon_unselected_1_2_0);
                }

        );

        RxViewHelper.getInstance().clicks(payCashFl2, aVoid ->
                {
                    //点击支付宝支付
                    state = 1;
                    payCashImg2.setImageResource(R.drawable.icon_selected_2_0);
                    payCashImg1.setImageResource(R.drawable.icon_unselected_1_2_0);

                }

        );

        RxViewHelper.getInstance().clicks(payCashSubmit, aVoid ->
                {
                    if (state == 0) {
                        //微信支付
                        Log.d("支付方式", "initView: 微信支付");
                        Intent intent = new Intent(PayCashActivity.this, WXPayEntryActivity.class);
                        intent.putExtra("url", creatOrderEntity.getWxString());
                        startActivity(intent);
                    } else {
                        //支付宝支付
                        Log.d("支付方式", "initView: 支付宝支付");
                        doAliPay();
                    }
                }

        );
    }

    //支付宝支付
    private void doAliPay() {
//        if (creatOrderEntity.getAliString()!=null){
//            Log.d(TAG, "doAliPay: "+creatOrderEntity.getAliString());
//            return;
//        }
        Runnable payRunnable = () -> {
            PayTask alipay = new PayTask(PayCashActivity.this);
            Map<String, String> result = alipay.payV2(creatOrderEntity.getAliString(), true);
            Message msg = new Message();
            msg.what = SDK_PAY_FLAG;
            msg.obj = result;
            mHandler.sendMessage(msg);
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void payResult() {
        finish();
    }
}
